﻿package com.firewolf.shiro.authentication.strategy;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.pam.AbstractAuthenticationStrategy;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.util.CollectionUtils;

/**
 * @Description: 自定义策略，至少保证有两个Realm可以认证通过
 * @Author: 刘兴
 * @Date : 2016年7月21日
 * @package : com.firewolf.shiro.authentication.strategy
 * @Java_Version : 1.7
 * @Version : 2016年7月21日上午11:23:15
 */
public class AtLeastTwoAuthenticatorStrategy extends AbstractAuthenticationStrategy {


    @Override
    public AuthenticationInfo afterAllAttempts(AuthenticationToken token, AuthenticationInfo aggregate) throws AuthenticationException {
        if (aggregate == null || CollectionUtils.isEmpty(aggregate.getPrincipals()) || aggregate.getPrincipals().getRealmNames().size() < 2) {
            throw new AuthenticationException("Authentication token of type [" + token.getClass() + "] " +
                    "，请保证至少有两个Realm认证通过！");
        }
        return aggregate;
    }
}
